<?php
function game_go(&$arrReturn)
{
	global $db;
	$speNo = $_GET['no'];
	$nowTime = strtotime(date('Y-m-d H:i:s',time()));
	$BeginTime = strtotime(date('Y-m-d',time()) . " 19:10:00");
	$EndTime = strtotime(date('Y-m-d',time()) . " 20:00:00");

	if($nowTime > $BeginTime && $nowTime < $EndTime)
	{
		//取下期时间
		$sql = "SELECT id,kgtime FROM gamecan28 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = $rs['kgtime'];
		}
		else
		{
			$sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
			$query = $db->query($sql);
			$rs = $db->fetch_array( $query );
			$arrRet['nextid'] ='0';
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		$arrReturn['msg'] = 'not in open game time(can)';
		return;
	}
	$No = intval($speNo);
	$arrCatchNo = array();
	if($speNo == 0)
	{
		$sql = "SELECT id FROM gamecan28 WHERE kj = 0 AND kgtime < NOW() AND kgtime > DATE_ADD(NOW(),INTERVAL -3 HOUR) 
		        and id not in(select gameno from game_result where gametype = 'gamecan')
				ORDER BY id DESC";
		$sql = "SELECT id FROM gamecan28 WHERE kj = 0 AND kgtime < NOW() AND kgtime > DATE_ADD(NOW(),INTERVAL -3 HOUR) 
		        and id not in(select gameno from game_result where gametype = 'gamecan')
				ORDER BY id DESC";
		$query = $db->query($sql);
		$i = 0;
		while($rs = $db->fetch_array( $query ))
		{
			$arrCatchNo[$i] = $rs["id"];
			$i++;
		}

	}
	else
	{
		$sql = "SELECT id FROM gamecan28 WHERE kj = 0 and id = '{$No}' ";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrCatchNo[0] = $rs["id"];
		}
		else
		{
			$arrReturn['code'] = "ok";
			$arrReturn['msg'] = "{$No} had opened(can)";
			$arrReturn['log'] .= LogFormat("{$No} had opened(can)");
			return;
		}
	}

	if(count($arrCatchNo) == 0)
	{
		CatchResult($arrCatchNo);
		$arrReturn['code'] = "ok";
		$arrReturn['no'] = "0";
		$arrReturn['msg'] = "no record to catch(can)";
		$arrReturn['log'] .= LogFormat("no record to catch(can)");
		return;
	}
	$ret = CatchResult($arrCatchNo);
	if($ret == "time_interval_err")
	{
		$arrReturn['code'] = "ok";
		$arrReturn['msg'] = "time_interval_error";
		$strlog = "time interval error(can)";
		$arrReturn['log'] .= LogFormat($strlog);
		return;
	}
	if ( $ret != "")
	{
		$arrReturn['code'] = "ok";
		$arrRet['nextid'] = "catch_ok";
		$arrReturn['msg'] = "catch_ok";
		$arrReturn['no'] = $ret;
		$strlog = "catched hg: {$ret},result had been saved(can)";
		$arrReturn['log'] .= LogFormat($strlog);
	}
	else //取不到结果
	{
		$ret = implode(',',$arrCatchNo);
		$arrReturn['code'] = 'noreward';
		$arrReturn['no'] = $ret;
		$arrReturn['msg'] = "can not catch {$ret} result(can)";
		$arrReturn['log'] = LogFormat("can not catch {$ret} result!(can)");
	}


}
function GetGame36Result($a,$b,$c)
{
	$arrNum = array($a,$b,$c);
	sort($arrNum);
	if($arrNum[0] == $arrNum[2]) //豹子
		return 1;
	if($arrNum[0] == $arrNum[1] || $arrNum[1] == $arrNum[2]) //对子
		return 2;
	if($arrNum[1] - $arrNum[0] == 1 && $arrNum[2] - $arrNum[1] == 1) //顺子
		return 3;
	if($arrNum[1] - $arrNum[0] == 1 || $arrNum[2] - $arrNum[1] == 1) //半顺
		return 4;
	return 5; //杂
}
function GetDiffHourCanadaToChina($theDate)
{
	global $db;
	$diffHour = 16;
	$Year = date("Y",strtotime($theDate));
	$beginTime = "";
	$endTime = "";
	$sql = "select c_begintime,c_endtime from canada_timezone where c_year = {$Year}";
	$query = $db->query($sql);
	if($rs = $db->fetch_array( $query ))
	{
		$beginTime = $rs['c_begintime'];
		$endTime = $rs['c_endtime'];
		if(strtotime($theDate) >= strtotime($beginTime) && strtotime($theDate) < strtotime($endTime))
			$diffHour = 15;
	}
	return $diffHour;
}

function CatchResult($arrReward)
{
	global $db;
	$ret = "";
	$arr = GetGameResult_can();
	if(is_array($arr))
	{
		if(count($arr) > 2) //检测时间差
		{
			$interval_time_sec = 210;
			$sql = "select no_interval_second from game_catch_config where gamekind = 'gamecan'";
			$query = $db->query($sql);
			if($rs = $db->fetch_array( $query ))
			{
				$interval_time_sec = $rs['no_interval_second'];
			}
			$Time1 = strtotime($arr[0]["time"]);
			$Time2 = strtotime($arr[1]["time"]);
			$newIntervalTime = $Time1 - $Time2;
			if($arr[0]['no'] - $arr[1]['no'] == 1 && $newIntervalTime <> $interval_time_sec && $newIntervalTime < 300) //时间间隔对不上，停止开奖
			{
				$sql = "insert into system_msg(msg_type,msg_content,msg_time) 
	        				values('采集问题','系统检测到两盘时间间隔{$newIntervalTime}与设定值{$interval_time_sec},不一致，暂停了采集结果!')";
				$query = $db->query($sql);
				return "time_interval_err";
			}
		}
		//生成新期号
		$sql = "call web_gameno_addcan({$arr[0]['no']},'{$arr[0]['time']}',10)";
		$arrResult = $db->Mysqli_Multi_Query($sql);
	}
	else
	{
		$arr = GetRameResult_168kai();
	}
	//print_r($arr);
	//处理结果
	foreach($arrReward as $key => $v)
	{
		$rewardstr = "";
		if(is_array($arr))
		{
			$numberstr = "";
			for($i = 0; $i < count($arr); $i++)
			{
				if($arr[$i]["no"] == $v)
				{
					$numberstr = str_replace(",","|",$arr[$i]["kjstr"]);
					break;
				}
			}

			if(strlen($numberstr) > 0)
			{
				$sql = "call web_savecatch_result('gamecan',{$v},'{$numberstr}')";
				$arrT = $db->Mysqli_Multi_Query($sql);
				$ret .= $v . " ";
			}
		}
	}
	return $ret;
}

function GetRameResult_168kai()
{
	$ret = "";
	$arrRet = array(array('no'=>'','time'=>'','kjstr'=>''));
	$specNo = intval($_GET['no']);
	$url = "http://www.168kai.com/Open/CurrentOpen?code=10041&_=" . rand(100000,999999);
	$kjcontent = file_get_contents($url);
	$arr = json_decode($kjcontent,true);
	$arrList = $arr;

	if(count($arrList) == 0) return "";

	for($i = 0;$i < count($arrList);$i++)
	{
		if( $specNo == 0 && $i > 20) break;
		$arrRet[$i]['no'] = $arrList[$i]['c_t'];
		$arrRet[$i]['time'] = "";
		$arrRet[$i]['kjstr'] = $arrList[$i]['c_r'];
	}
	return $arrRet;
}


function GetGameResult_can()
{
	$url = "http://203.88.161.240:899/jndcj/jndcj.php";
	$kjcontent = file_get_contents( $url );
	$arr = json_decode($kjcontent,true);
	if(!is_array($arr))
	{
		return "";
	}
	$arrRet = array(array('no'=>'','time'=>'','kjstr'=>''));
	$specNo = intval($_GET['no']);
	$diffHour = 15;
	for($i = 0; $i < count($arr); $i++)
	{
		if( $specNo == 0 && $i > 20) break;
		$arrRet[$i]['no'] = $arr[$i]["drawNbr"];
		$day = date("Y-m-d",strtotime($arr[$i]['drawDate']));
		$tim = date("H:i:s",strtotime($arr[$i]['drawTime'] ));
		$openTime = $day." ". $tim;
		if($i == 0) //更新时差
			$diffHour = GetDiffHourCanadaToChina($openTime);
		$arrRet[$i]['time'] = date("Y-m-d H:i:s",strtotime($day." ". $tim . " +{$diffHour} hour"));
		$arrRet[$i]['kjstr'] = implode(",",$arr[$i]['drawNbrs']);
	}
	return $arrRet;
}

error_reporting( 0 );
set_time_limit(200);
include_once( "inc/conn.php" );
include_once( "inc/function.php" );

if ( $_GET['key'] == "catch_result_can" )
{
	$arrRet = array('code'=>'ok', //
		'no' =>'',
		'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
		'log'=>'',
		'nextid'=>'', //下一盘id
		'nexttime'=>'' //下一篇开奖时间
	);
	game_go($arrRet);
	if ($arrRet['nextid'] == 'catch_ok')
	{
		$RandSecond = rand(30,40);
		$sql = "SELECT id,DATE_ADD(kgtime,interval {$RandSecond} second) kgtime FROM gamecan28 WHERE kj = 0 AND kgtime > NOW() limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = $rs['kgtime'];
		}
		else
		{
			$arrRet['nextid'] ='0';
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
	}
	else
	{
		$RandSecond = rand(20,30);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from gamecan28 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
	}
	//返回
	echo json_encode($arrRet);
}

$db->close( );
